package ru.arriah.servicedesk.web.leadExecutor.action;

import java.io.IOException;
import java.text.DateFormat;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.Locale;

import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ru.arriah.common.web.action.ActionMapping;
import ru.arriah.common.web.action.DumbAction;
import ru.arriah.servicedesk.bean.RequestStatusBean;
import ru.arriah.servicedesk.bean.TaskBean;
import ru.arriah.servicedesk.ejb.RequestManagerLocalHome;
import ru.arriah.servicedesk.ejb.RequestManagerLocalObject;
import ru.arriah.servicedesk.help.Utils;
import ru.arriah.servicedesk.web.commonaction.exception.InternalException;


public class TaskSearchFormAction extends DumbAction {
   protected RequestManagerLocalHome requestManagerHome;

   public TaskSearchFormAction() throws NamingException {
      super();
      requestManagerHome =
         Utils.getRequestManagerHomeInterface();
   }
   
   
   /**
    * Restore TaskBean from HTTP request
    * @param request
    * @return
    */
   private TaskBean restoreBean(HttpServletRequest request) {
      TaskBean taskTemplate = new TaskBean();
      DateFormat dateformat = 
          DateFormat.getDateInstance(
             DateFormat.SHORT, 
             new Locale("ru")
          );
            
      taskTemplate.setStatusId(idVal(request.getParameter("status_query")));
      taskTemplate.setId(idVal(request.getParameter("id_query")));
      taskTemplate.setText(request.getParameter("text_query"));                        
      
      try {
         taskTemplate.setSearchFromStartDate(
            dateformat.parse(request.getParameter("fromStartDate"))
         );
      } catch (Exception e) {
         taskTemplate.setSearchFromStartDate(
            new Date()
         );
      }
      
      try {
         taskTemplate.setSearchToStartDate(
            dateformat.parse(request.getParameter("toStartDate"))
         );
      } catch (Exception e) {
         taskTemplate.setSearchToStartDate(
            new Date()
         );
      }
      
      try {
         taskTemplate.setSearchFromEndDate(
            dateformat.parse(request.getParameter("fromEndDate"))
         );
      } catch (Exception e) {
         taskTemplate.setSearchFromEndDate(
            new Date()
         );
      }
      
      try {
         taskTemplate.setSearchToEndDate(
            dateformat.parse(request.getParameter("toEndDate"))
         );
      } catch (Exception e) {
         taskTemplate.setSearchToEndDate(
            new Date()
         );
      }
      
      int userId = Utils.getUserId(request);
      taskTemplate.setEmployeeId(userId);
      
      return taskTemplate;
   }
   
   
   
   public String execute(
      ActionMapping actionMapping,
      HttpServletRequest request,
      HttpServletResponse response
   ) throws IOException, ServletException {
      try {                 
        RequestManagerLocalObject requestManager = 
          requestManagerHome.create();                                     
        
        Collection<RequestStatusBean> statusList = 
           requestManager.selectRequestStatuses();
        
        Date toStartDate = new Date();
        Date toEndDate = new Date();
        Date fromStartDate = new Date();
        Date fromEndDate = new Date();
        
        requestManager.remove();                                                               
                
        Action action = Action.valueOf(actionMapping.getActionName());
        
        switch (action) {
        case displayTaskSearchForm:
           Calendar calendar = Calendar.getInstance();
           toStartDate = calendar.getTime();
           toEndDate = calendar.getTime();
           
           calendar.add(Calendar.MONTH, -1);
           
           fromStartDate = calendar.getTime();
           fromEndDate = calendar.getTime();
        break;
        
        
        case processTaskSearchForm:
           TaskBean taskTemplate = 
              restoreBean(request);                      
              
           toStartDate = 
              taskTemplate.getSearchToStartDate();           
           toEndDate = 
              taskTemplate.getSearchToEndDate();            
           fromStartDate = 
              taskTemplate.getSearchFromStartDate();            
           fromEndDate = 
              taskTemplate.getSearchFromEndDate();
           
           request.getSession().setAttribute("searchTaskTemplate", taskTemplate);
           request.getSession().setAttribute("sidebarpage", 0);
           
           addInfMessage(request, config.getProperty("INF.SEARCH_COMPLEATED"));
        break;

        default:
           throw new RuntimeException("Unsupported action " + action);
        }
                
        request.setAttribute("statusList", statusList);
        
        request.setAttribute("toStartDate", toStartDate);                        
        request.setAttribute("toEndDate", toEndDate);                
        request.setAttribute("fromStartDate", fromStartDate);                        
        request.setAttribute("fromEndDate", fromEndDate);
                               
        return actionMapping.getSuccessTarget();
      } catch (Exception e) {
         handleException(e, "execute");
         throw new InternalException("ErrorMessage.internal");
      }
   }
}